#include "device.h"
#include <pthread.h>

pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;

void log_int(DeviceManager *msg) {
    pthread_mutex_lock(&log_mutex);
    if (msg == NULL) {
        fprintf(stderr, "log_int: 无效的 msg 指针\n");
        pthread_mutex_unlock(&log_mutex);
        return;
    }
    FILE *log_file = fopen("device.log", "a");
    if (!log_file) {
        perror("打开失败");
        pthread_mutex_unlock(&log_mutex);
        return;
    }
    time_t now = time(NULL);
    char time_str[20];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now));
    fprintf(log_file, "[%s] %s 值: %.2f\n", time_str, msg->name, msg->value);
    fclose(log_file);
    pthread_mutex_unlock(&log_mutex);
}

void time_change(DeviceManager *device) {
    pthread_mutex_lock(&log_mutex);
    if (device == NULL) {
        fprintf(stderr, "time_change: 无效的设备指针\n");
        pthread_mutex_unlock(&log_mutex);
        return;
    }
    FILE *log_file = fopen("device.log", "a");
    if (!log_file) {
        perror("打开失败");
        pthread_mutex_unlock(&log_mutex);
        return;
    }
    time_t now = time(NULL);
    char time_str[20];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now));

    char log_message[200];
    int ret;
    if (device->Type == SENSOR_TEMP || device->Type == SENSOR_HUMIDITY || device->Type == SENSOR_LIGHT) {
        ret = snprintf(log_message, sizeof(log_message),
                       "传感器 %s 在时间 %s 发生变化, 值: %.2f",
                       device->name, time_str, device->value);
    } else {
        const char *status = (device->value == 0.0) ? "关闭" : "开启";
        ret = snprintf(log_message, sizeof(log_message),
                       "执行器 %s 在时间 %s %s",
                       device->name, time_str, status);
    }
    if (ret < 0 || ret >= sizeof(log_message)) {
        fprintf(stderr, "日志消息格式化失败\n");
        fclose(log_file);
        pthread_mutex_unlock(&log_mutex);
        return;
    }
    fprintf(log_file, "%s\n", log_message);
    fclose(log_file);
    pthread_mutex_unlock(&log_mutex);
}